# 获取当前用户（auth/deps.py）
from fastapi import Depends, HTTPException
from jose import JWTError, jwt
from app.auth.auth import oauth2_scheme
from app.core.security import SECRET_KEY, ALGORITHM
from app.models.user import User


async def get_current_user(token: str = Depends(oauth2_scheme)):
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username = payload.get("sub")
        if not username:
            raise HTTPException(status_code=401, detail="认证失败")
    except JWTError:
        raise HTTPException(status_code=401, detail="令牌无效")

    user = await User.get_or_none(username=username)
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    return user


def require_role(required_roles: list[str]):
    async def checker(current_user: User = Depends(get_current_user)):
        if current_user.role.name not in required_roles:
            raise HTTPException(status_code=403, detail="权限不足")
        return current_user

    return checker
